clear all;

load('input.mat','distance','Pi')
totalPi=sum(Pi);

cd ..; cd ..; cd ..;
load('code_main_model\6_implied_w_r\computation_results\data.mat','chi','beta',...
    'credit','nmkt','h','period_trans','nyears');
load('code_main_model\6_implied_w_r\input\comm_loc_model.mat','comm_loc_model');
cd 'code_figure_table\OA\Figure OA20';


for i_t=nyears+1:period_trans
    comm_loc_model(:,i_t)=comm_loc_model(:,nyears);
end

profit(1:period_trans-1,1:nmkt)=0;
for i_t=1:period_trans-1
    % decide for each market, where is the cloest accessible bank
    cloest_accessible(1:nmkt,1)=0;
    for i_mkt=1:nmkt
        % if there is a bank in this market, then it is the closest
        if (comm_loc_model(i_mkt,i_t)==1)
            cloest_accessible(i_mkt)=i_mkt;
        else
            temp_dist=distance(i_mkt,:);
            temp_dist(Pi>h | comm_loc_model(:,i_t)==0)=inf; % markets with too high pop den are not accessible
            [~,cloest_accessible(i_mkt)]=min(temp_dist);
        end
    end
    
    bank=find(comm_loc_model(:,i_t)==1);
    nbank=length(bank);

    for i_mkt=1:nbank
        mkt_index=bank(i_mkt);
        mkt_profit=find(cloest_accessible==mkt_index);
        profit(i_t,mkt_index)=sum(credit(i_t,mkt_profit))*chi*beta^(i_t-1);
    end
end
profit=sum(profit,1)*totalPi;
